package main

import (
	"encoding/json"
	"github.com/julienschmidt/httprouter"
	"io"
	"io/ioutil"
	"net/http"
	"video_server/api/dbops"
	"video_server/api/defs"
	"video_server/api/session"
)

/**
1. 将request.body转换为结构体
2. 添加用户
3. 服务端保存用户session
4. 返回成功登录信息
*/
func CreatorUser(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
	res, _ := ioutil.ReadAll(r.Body)
	userBody := &defs.UserCredential{}
	//将 请求体中的json字符转换为结构体
	if err := json.Unmarshal(res, userBody); err != nil {
		sendErrorResponse(w, defs.ErrorRequestBodyParseFailed)
		return //直接返回是因为sendErrorResponse已经将信息返回了
	}

	if err := dbops.AddUserCredential(userBody.Username, userBody.Pwd); err != nil {
		sendErrorResponse(w, defs.ErrorDBError)
	}

	sessionID := session.GenerateNewSessionID(userBody.Username)
	su := &defs.SignedUp{
		Success:   true,
		SessionId: sessionID,
	}

	if resp, err := json.Marshal(su); err != nil {
		sendErrorResponse(w, defs.ErrorInternalFaults)
		return
	} else {
		sendNormalResponse(w, string(resp), 201)
	}

}

func Login(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
	uname := p.ByName("user_name")
	io.WriteString(w, uname)
}
